import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
let scene, camera, renderer, controls

function init() {
  scene = new THREE.Scene()
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  camera.position.set(0, 0, 5)
  renderer = new THREE.WebGLRenderer({ antialias: true })
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  controls = new OrbitControls(camera, renderer.domElement)
  controls.enableDamping = true

  const axesHelper = new THREE.AxesHelper(5)
  scene.add(axesHelper)
};

function createBasic () {
  // 1. 创建缓冲集合体
  const geometry = new THREE.BufferGeometry()
  // 2. 创建顶点坐标
  const vertices = new Float32Array([
    0, 0, 0,
    1, 0, 0,
    0, 1, 0,
    1, 0, 0,
    1, 1, 0,
    0, 1, 0
  ])
  // 3. 设置位置属性
  const position = new THREE.BufferAttribute(vertices, 3)
  geometry.setAttribute('position', position)

  // 设置颜色属性
  const colorArr = new Float32Array([
    0, 1.0, 0,
    1.0, 0, 0,
    0, 1.0, 0,
    1.0, 0, 0,
    1.0, 0, 0,
    0, 1.0, 0
  ])
  const color = new THREE.BufferAttribute(colorArr, 3)
  geometry.setAttribute('color', color)

  // 4. 创建材质
  const material = new THREE.MeshBasicMaterial({
    vertexColors: true, // 支持顶点着色
  })
  // 5. 创建物体
  const mesh = new THREE.Mesh(geometry, material)
  scene.add(mesh)
}

function renderLoop() {
  renderer.render(scene, camera)
  controls.update()
  requestAnimationFrame(renderLoop)
}

init()
createBasic()
renderLoop() 

